package com.dk.util.http.req;

import com.dk.domain.ApiAutoTestEntity;
import com.dk.util.String.StringUtil;
import com.dk.util.config.ReadConfig;
import com.dk.util.http.OkHttpBuild;
import com.dk.util.json.JsonUtil;
import com.dk.util.log.Log;
import com.google.common.base.Strings;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * DELETE请求实现类
 */
public class DeleteHandler implements ReqStrategy{
    /**
     * DELETE请求实现类
     * @param apiAutoTestEntity
     * @return
     */
    @Override
    public Response request(ApiAutoTestEntity apiAutoTestEntity) {
        //请求对象
        Request req;
        //响应对象
        Response res = null;
        //头部信息
        String headers = apiAutoTestEntity.getHeaders();
        //拼接协议版本+域名或ip+路由
        String url = StringUtil.splicingProtocolAndUrl(apiAutoTestEntity.getProtocol(), apiAutoTestEntity.getUrl());
        //请求主体对象
        RequestBody requestBody = null;
        //获取请求体对象
        if(!Strings.isNullOrEmpty(apiAutoTestEntity.getBodyType())){
            //获取请求体对象
            requestBody = GainReqBody.getReqBodyOnType(apiAutoTestEntity.getBodyType(), apiAutoTestEntity.getBody());
        }
        //请求头不为空时,增加头部信息
        if (!Strings.isNullOrEmpty(headers)) {
            //获取请求头String类型Map
            Map<String, String> headersMapForString = JsonUtil.parseJsonToHashMapForString(headers);
            //构造请求对象
            req = new Request
                    .Builder()//开始构建
                    .delete(requestBody)//使用post请求方式,携带请求体
                    .headers(Headers.of(headersMapForString))//添加消息头
                    .url(url)//设置地址对象
                    .build();//构建完成
        } else {
            req = new Request
                    .Builder()//开始构建
                    .delete(requestBody)//使用post请求方式,携带请求体
                    .url(url)//设置地址对象
                    .build();//构建完成
        }
        //获取通讯对象
        Call call = OkHttpBuild.okHttpClient.newCall(req);
        try {
            //发送请求
            res = call.execute();
        } catch (IOException e) {
            Log.error("---【error】:发送POST请求io异常,用例编码:" + apiAutoTestEntity.getCaseNum() + ";");
        }
        return res;
    }

}
